//
//  LoginViewController.m
//  PropertyMananger
//
//  Created by bh on 16/12/26.
//  Copyright © 2016年 BH. All rights reserved.
//

#import "LoginViewController.h"
#import "MineViewController.h"
#import "LoginView.h"
#import "BHMainTabbarController.h"
#import "UserInfoModel.h"
#import "HomeViewController.h"
@interface LoginViewController ()
@property (nonatomic,strong) LoginView * loginView;

@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSString *userPassword;

//记录 记住密码 按钮的选中状态
@property (nonatomic,strong)NSNumber *isRembPwd;
//记录 自动登录 按钮的选中状态
@property (nonatomic,strong)NSNumber *isAutoLogin;

//记录退出登录按钮的点击状态
@property (nonatomic,strong)NSNumber *isloging;

@property (nonatomic,strong)NSNumber *InitRembPwd0;
@property (nonatomic,strong)NSNumber *InitAutoLogin0;

@property (nonatomic,copy) NSString * communityName;//小区名字


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
     self.title = @"登录";
    
     [self setupUI];
    
    //取出当前本地数据赋值给当前控件
    [self takeOutLocalDataForView];
    
       // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
    
    
}
- (void)setupUI
{

    self.loginView = [[LoginView alloc]initWithFrame:CGRectMake(0, 0, BHscreenW, BHscreenH)];
    [self.view addSubview:self.loginView];
    
    //记住密码点击事件
    [self.loginView.remenberPwBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    //自动登录点击事件
    [self.loginView.autoLoginBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    //登录点击事件
    [self.loginView.loginButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    self.loginView.accountTF.clearButtonMode = UITextFieldViewModeWhileEditing;

}
- (void)buttonClick:(UIButton *)button
{
    if(button.tag == 100)
    { //----记住密码

        [self rembPwdBtnClick:button];
        
    }else if(button.tag == 101)
    {//-----自动登录
        
        [self autoLoginBtnClick:button];
    }
    else if (button.tag == 102)
    {//-----登录
      
        //获取登录的数据
     
        [self loginWith:button];
    }

}
//记住按钮点击
-(void)rembPwdBtnClick:(UIButton *)button{
    //记住密码按键取消选中  自动登录也取消选中
    if (self.loginView.remenberPwBtn.selected == YES) {
        self.loginView.remenberPwBtn.selected = NO;
        self.loginView.autoLoginBtn.selected = NO;
    }else{
        self.loginView.remenberPwBtn.selected = YES;
    }
}
//自动登录按键
-(void)autoLoginBtnClick:(UIButton *)button{
    //自动登录按键选中   记住密码也选中
    if (self.loginView.autoLoginBtn.selected == YES) {
        self.loginView.autoLoginBtn.selected = NO;
    }else{
        self.loginView.autoLoginBtn.selected = YES;
        self.loginView.remenberPwBtn.selected = YES;
    }
}

- (void)loginWith:(UIButton *)button
{
    
    DLog(@"%@%@",self.loginView.accountTF.text , self.loginView.passwordTF.text);
    if(!self.loginView.accountTF.text.length){//账号栏没有值
        [MBProgressHUD shownews:@"请输入登录账号" time:1.5];
        return;
        
    }else if (self.loginView.passwordTF.text.length <6 || self.loginView.passwordTF.text.length >16){
    
        [MBProgressHUD shownews:@"请输入6~16位的密码" time:1.5];
    }else{//账号栏有值
        
        self.userName = self.loginView.accountTF.text;
        if (!self.loginView.passwordTF.text.length) {//密码为空
            [MBProgressHUD shownews:@"请输入密码!" time:1.5];
            return ;
            
        }
        else{//密码有值
            
            //加密
            self.userPassword = [BHEncryption encode:self.loginView.passwordTF.text key:Key];//密码 需要加密
            
            if(self.loginView.remenberPwBtn.selected){//记住密码按键状态为选中则保存密码和账号
                //保存用户名到沙盒中
                [[NSUserDefaults standardUserDefaults] setObject:self.userName forKey:Account];
                
                //保存用户密码到沙盒中
                [[NSUserDefaults standardUserDefaults] setObject:self.userPassword forKey:Password];
            }
            
         
            //保存 记住密码 按钮的选中状态
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:self.loginView.remenberPwBtn.selected] forKey:RemberPassword];
            
            //获取登录数据
            [self postLoginData];
        }
    }
}
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
#pragma mark - 登录网络请求
UserInfoModel const * userModel;
- (void)postLoginData
{
    //取消之前的请求
    BOOL isconect = [BHCommonAppDelegate isConnectionAvailable];
    if (isconect) {//有网络
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"正在登录中...";
        // 隐藏时从父控件中移除
        hud.removeFromSuperViewOnHide = YES;
        // YES代表需要蒙版效果
        hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.userInteractionEnabled = YES;
        
    }else{//没网络
        return;
    }

    
    NSDictionary * params = @{@"LoginName":self.userName,
                              @"Password":self.userPassword,
                              @"json":@"\{\"jsonEntity\":\{},\"action\":\"applogin\",\"version\":\"V1.0\"}"
                              };
    
    [UserNetWorkRequset postLoginSuccess:^(id data) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        [MBProgressHUD hideHUDForView:self.view];

      NSString * code = [NSString stringWithFormat:@"%@",dict[@"Code"]];
         if([code isEqualToString:@"1"]){//登录成功
             NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
             NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
             NSDictionary * dict2 = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
             DLog(@"登录信息的数据 == %@",dict2);
             
             
             UserInfoModel * model = [[UserInfoModel alloc]init];
             [model setValuesForKeysWithDictionary:dict2];
             userModel = model;
//             DLog(@"用户的登录名===%@",model.LoginName);
             self.communityName = model.CommunityName;
//             DLog(@"小区名== %@",self.communityName)
             NSDictionary * dict = @{@"key":self.communityName};
             DLog(@"提交的小区 === %@",dict);
              [[NSNotificationCenter defaultCenter] postNotificationName:communityNameNoticeCenter object:nil userInfo:dict];
             
            
             //保存 自动登录 按钮的选中状态
             [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:self.loginView.autoLoginBtn.selected] forKey:AutoLogin];
             //保存用户名到沙盒中
             [[NSUserDefaults standardUserDefaults] setObject:self.userName forKey:Account];
             //保存用户密码到沙盒中
             [[NSUserDefaults standardUserDefaults] setObject:self.userPassword forKey:Password];
             
             
             DLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:Password]);
             
             AppDelegate * appdelagete = (AppDelegate *)[UIApplication sharedApplication].delegate;
             [appdelagete setRoot];
              [MBProgressHUD showSuccess:@"登录成功" time:1.5];
             
             //极光推送设置别名
             [JPUSHService setTags:nil aliasInbackground:model.LoginName];
             
         }else{//失败
             
             [MBProgressHUD showError:dict[@"Msg"] time:1.5];
         }
       
        
        
    } Fail:^(NSString *errorDes) {
        [MBProgressHUD hideHUDForView:self.view];
        DLog(@"%@",errorDes);
    } param:params];
    
}
#pragma mark - 获取数据
- (void)postWorkNumData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    
    NSDictionary * parms = nil;
    parms = @{
              @"WorkerId":userModel.WorkerID,
              @"CommunityID":userModel.CommunityID,
              @"json":@"\{\"jsonEntity\":\{},\"action\":\"incompletetask\",\"version\":\"V1.0\"}"
              };
    
    [WorkOrderRequest postWorkNumSuccess:^(id data) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"tabbar 获取的工单数量的数据 == %@",array);
          UserInfoModel * model = [[UserInfoModel alloc]init];
        for (NSDictionary * dict in array) {
            
//            self.complainttotalCount = dict[@"AllComplaintcount"];
//            self.repairtotalCount = dict[@"AllRepaircount"];
//            DLog(@"报修单数量 == %@",self.repairtotalCount);
            
            [model setValuesForKeysWithDictionary:dict];
            userModel = model;
            
        }
        
        //  [self.mTableView reloadData];
    } Fail:^(NSString *errorDes) {
        [MBProgressHUD hideHUD];
    } param:parms];
    
}


//取出当前本地数据赋值给当前控件
-(void)takeOutLocalDataForView{
    
    //判断自动登录按钮 和 记住密码的 初始状态
    NSNumber * rembPwd = [[NSUserDefaults standardUserDefaults] objectForKey:RemberPassword];
    NSNumber * autoLogin = [[NSUserDefaults standardUserDefaults] objectForKey:AutoLogin];
    DLog(@"记住密码=== %@ 自动登录=== %@",rembPwd,autoLogin);
    
    if([rembPwd boolValue]){//记住密码
        self.loginView.remenberPwBtn.selected = [rembPwd boolValue];
        self.userName = [[NSUserDefaults standardUserDefaults] objectForKey:Account];
        self.loginView.accountTF.text = self.userName;
        self.userPassword = [[NSUserDefaults standardUserDefaults] objectForKey:Password];
        self.loginView.passwordTF.text = [BHEncryption decode:self.userPassword key:Key];//解密
        if([autoLogin boolValue]){//自动登录
            self.loginView.autoLoginBtn.selected = [autoLogin boolValue];
            //获取登录数据
            [self postLoginData];
        }

    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];

}

@end
